package com.sky.controller.admin;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: HuoXu
 * @Date: 2023/07/18/17:32
 * @Description: 快乐跳跳虎
 */

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口实现文件上传用于阿里云oss
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传,{}",file);
        try {
            //获取文件的原始名称拿到后缀
            String originalFilename = file.getOriginalFilename();
            //截取文件后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //使用uuid随机创建文件名称
            String newFileName = UUID.randomUUID().toString() + extension;
            //文件的返回路径
            String filePath = aliOssUtil.upload(file.getBytes(), newFileName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败,{}",e);
        }
        //将文件名设置成uuid
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
